import { Ref, onMounted } from "vue";

function useInView(ref: Ref) {
  const callback = (entries: IntersectionObserverEntry[]) => {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if (entry.intersectionRatio <= 0) return; // 如果元素不可见，则不执行任何操作
      let img = entry.target;
      if (entry.isIntersecting) {
        console.log(img.attributes);
        let src = img.getAttribute("data-src");
        img.setAttribute("src", src);
        img.removeAttribute("data-src");
        observer.unobserve(img);
      }
      // if (entry.isIntersecting) {
      //   // dom.src = dom.dataset.src;
      //   // dom.removeAttribute("data-src");
      //   // dom.removeAttribute("loading");
      // }
    });
  };
  const options = {
    root: null,
    rootMargin: "0px",
    threshold: 0.1,
  };
  const observer = new IntersectionObserver(callback, options);
  onMounted(() => {
    console.log(ref.value);

    const list = Object.keys(ref.value);
    console.log(list);
    list.forEach((item) => {
      observer.observe(ref.value[item]);
    });
  });
  // [...dom].forEach((item) => {
  //   console.log(item);

  //   observer.observe(item);
  // });
}

export { useInView };
